const http = require('http');
const url = require('url');
const mime = require('mime');

const server = http.createServer();

server.on('request', (req, res) => {
    // 获取浏览器发生的请求
    console.log(req.url);
    // console.log(url.parse(req.url, true));    
    // res.end('111');    
    // 代理服务器向资源服务器发生请求 
    const option = {
        hostname: 'localhost',
        port: 8888,
        path: req.url,
        method: 'GET',
        headers: {
            aa: 'bb'
        }
    }
    let str = '';
    const reqo = http.request(option, reso => {
        console.log('状态码：', reso.statusCode);
        // reso.setEncoding('utf8');
       
        reso.on('data', chunk => {
            str += chunk;
        });
        reso.on('end', () => {
            console.log('接受服务器返回完成了');      
            
            res.writeHead(200, {               
                // "Access-Control-Allow-Origin": "*",
                "content-type": mime.getType(req.url),
                "content-length":Buffer.byteLength(str)
            });          
            console.log(Buffer.from(str));            
            res.end(Buffer.from(str));   
            str = '';
        });        
    });

    reqo.setHeader('connection','keep-alive');
    reqo.setHeader('accept','image/webp,image/apng,image/*,*/*;q=0.8');
    reqo.setHeader('accept-encoding', 'gzip, deflate, br');

    reqo.on('error', e => {
        console.log('访问源服务器出错：', e.message);        
    })
    // 把资源服务器返回的结果 发送给目标服务器

    reqo.end();
});

server.listen(9999, () => { console.log('http://localhost:9999/index.html 服务器已启动') });


// connection: 'keep-alive',
// pragma: 'no-cache',
// 'cache-control': 'no-cache',
// 'user-agent':
//  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
// accept: 'image/webp,image/apng,image/*,*/*;q=0.8',
// referer: 'http://localhost:8888/index.html',
// 'accept-encoding': 'gzip, deflate, br',
// 'accept-language': 'zh-CN,zh;q=0.9' 